package com.mani.geotag;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Prepares a OAuthConsumer and OAuthProvider 
 * 
 * OAuthConsumer is configured with the consumer key & consumer secret.
 * OAuthProvider is configured with the 3 OAuth endpoints.
 * 
 * Execute the OAuthRequestTokenTask to retrieve the request, and authorize the request.
 * 
 * After the request is authorized, a callback is made here.
 * 
 */
public class PrepareRequestTokenActivity extends Activity {

	final String TAG = getClass().getName();
	
    private OAuthConsumer consumer; 
    private OAuthProvider provider;
    CircularApplication app;
    private WebView mWebView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	try {
    		this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
    	    this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
    	    this.provider.setOAuth10a(true);
    	} catch (Exception e) {
    		Log.e(TAG, "Error creating consumer / provider",e);
		}
    	app = (CircularApplication)this.getApplication();
    	mWebView = new WebView(this);
    	authenticate();
	}

	public void error() {
		   LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		   View layout;
	   	   layout = inflater.inflate(R.layout.custom_toast, null);
           TextView message = (TextView)layout.findViewById(R.id.message);
           message.setText("Error while accesing access token for twitter.");
           Toast toastView = new Toast(this);
           toastView.setView(layout);
           toastView.setDuration(Toast.LENGTH_LONG);
           toastView.setGravity(Gravity.CENTER, 0,0);
           toastView.show();
           finish();
	}

	private class RestWebViewClient extends WebViewClient {
      	 @Override
      	 public boolean shouldOverrideUrlLoading(WebView view, String url) {
      		 
      		 if (url.toString().startsWith(Constants.OAUTH_CALLBACK_URL)) {
      			getToken (Uri.parse(url));
      		 }
      		 return true;
      	 }	
	 }
         private void getToken (Uri uri) {
         	
     		String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
     		try {

     			provider.retrieveAccessToken(consumer, verifier);
				app.updateTwitterToken(consumer.getToken(), consumer.getTokenSecret());
				String token = app.getTwitterAccessKey();
				String secret = app.getTwitterAccessSecret();
				System.out.println("get token ********* "+token+":::"+secret);
				consumer.setTokenWithSecret(token, secret);
				PrepareRequestTokenActivity.this.finish();     			

     		} catch (OAuthMessageSignerException e) {
     			e.printStackTrace();
     		} catch (OAuthNotAuthorizedException e) {
     			e.printStackTrace();
     		} catch (OAuthExpectationFailedException e) {
     			e.printStackTrace();
     		} catch (OAuthCommunicationException e) {
     			e.printStackTrace();
     		}
         }
	public void authenticate()
	{
    	try {
    		this.setContentView (mWebView);
    		String authURL = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
			 mWebView.getSettings().setJavaScriptEnabled(true);
			 mWebView.loadUrl(authURL);
			 mWebView.setWebViewClient(new RestWebViewClient());
	    } catch (OAuthMessageSignerException e) {
	    	e.printStackTrace();
	    	
	    } catch (OAuthNotAuthorizedException e) {
	    	e.printStackTrace();
	    	
	    } catch (OAuthExpectationFailedException e) {
	    	e.printStackTrace();
	    	
	    } catch (OAuthCommunicationException e) {
	    	e.printStackTrace();
	    	
	    }

	}
	
}
